package club.zykeji.ddns.zyddnsclientjava.task;

import club.zykeji.ddns.zyddnsclientjava.util.HttpUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.util.TimerTask;

/**
 * Create by 丶TheEnd on 2020/5/5.
 * @author TheEnd
 */
@Component
@EnableScheduling
@Slf4j
public class DDNSTask extends TimerTask {

    @Autowired
    private HttpUtil httpUtil;

    @Override
    public void run() {
        try {
            task();
        } catch (Exception e) {
            System.out.println("发生异常了: " + e.getMessage());
        }
    }

    private void task() {
        String info = "本机IP为: {}, 原绑定IP为: {}, 解析结果: {}";
        String nativeIp = httpUtil.getNativeIp();
        String currentIp = httpUtil.getCurrentIp();
        if (StrUtil.hasBlank(nativeIp, currentIp)) {
            System.out.println("获取数据失败,请稍后再试");
            return;
        }
        System.out.println(StrUtil.format(info, nativeIp, currentIp, nativeIp != null && nativeIp.equals(currentIp)));

        // 判断是否需要执行更新
        if (nativeIp == null || !nativeIp.equals(currentIp)) {
            System.out.println("更新DNS解析");
            if (httpUtil.updateIp(nativeIp)) {
                System.out.println("更新成功");
            } else {
                System.err.println("更新失败");
            }
        }
    }

}
